package framework.core.controller;

import java.io.IOException;
import java.io.PrintWriter;
import java.util.Date;
import java.util.Enumeration;

import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import net.sf.json.JSONArray;
import net.sf.json.JSONObject;
import net.sf.json.JsonConfig;
import net.sf.json.util.CycleDetectionStrategy;

import org.slf4j.Logger;
import org.springframework.stereotype.Controller;

import framework.core.util.DateJsonValueProcessor;
import framework.core.util.SingletonLog;

/**
 * @ClassName: BaseAction 
 * @Description: 基础Controller类
 * @author: Ching Wang
 * @date 2013-5-18 下午1:00:28 
 *
 */
@SuppressWarnings("rawtypes")
@Controller
public class BaseAction {
	protected Logger logger = SingletonLog.getSingletonLog();
	
	/**
	 * @Title: jsoncfg 
	 * @Description: 读取Json，防止死循环错误以及时间字段的格式化
	 * @param pattern 时间格式yyyy-MM-dd HH:mm:ss
	 * @return
	 */
	private JsonConfig jsoncfg(String pattern) {
		JsonConfig cfg = new JsonConfig();
		cfg.setIgnoreDefaultExcludes(false);
		cfg.setCycleDetectionStrategy(CycleDetectionStrategy.LENIENT);// 防止死循环
		cfg.registerJsonValueProcessor(Date.class, new DateJsonValueProcessor(pattern)); // date processor register
		return cfg;
	}

	/**
	 * @Title: clearSession 
	 * @Description: 清空Session
	 * @param session
	 */
	public void clearSession(HttpSession session) {
		for (Enumeration items = session.getAttributeNames(); items.hasMoreElements();) {
			String item = (String) items.nextElement();
			session.removeAttribute(item);
		}
	}
	
	/**
	 * @Title: outJson 
	 * @Description: 输出Object对象
	 * @param response
	 * @param obj
	 * @param pattern
	 */
	public void outJson(HttpServletResponse response, Object obj, String pattern) {
		outString(response, JSONObject.fromObject(obj, jsoncfg(pattern)).toString());
	}

	/**
	 * @Title: outJsonArray 
	 * @Description: 输出Array对象
	 * @param response
	 * @param array
	 * @param pattern
	 */
	public void outJsonArray(HttpServletResponse response, Object array, String pattern) {
		outString(response, JSONArray.fromObject(array, jsoncfg(pattern)).toString());
	}

	/**
	 * @Title: outString 
	 * @Description: 输入String字符串
	 * @param response
	 * @param str
	 */
	public void outString(HttpServletResponse response, String str) {
		try {
			response.setContentType("text/html;charset=UTF-8");
			response.setCharacterEncoding("UTF-8");
			PrintWriter out = response.getWriter();
			logger.info(str);
			out.write(str);
			// 清空缓存
			out.flush();
			// 关闭流
			out.close();
		} catch (IOException e) {
			e.printStackTrace();
		}
	}
}
